package cn.wit.sst;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import cn.wit.sst.config.AppContextConfig;
import cn.wit.sst.domain.College;
import cn.wit.sst.domain.Course;
import cn.wit.sst.domain.Major;
import cn.wit.sst.mapper.CollegeMapper;
import cn.wit.sst.mapper.CourseMapper;
import cn.wit.sst.mapper.MajorMapper;
import cn.wit.sst.utils.AppCache;
import io.reactivex.Completable;
import io.reactivex.rxjavafx.schedulers.JavaFxScheduler;
import io.reactivex.schedulers.Schedulers;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

public class Main extends Application {
	private static final Logger logger = LoggerFactory.getLogger(Main.class);
	ApplicationContext context;

	public void start(Stage stage) throws Exception {
		context = new AnnotationConfigApplicationContext(AppContextConfig.class);

		FXMLLoader loader = new FXMLLoader(getClass().getResource("view/main.fxml"));
		loader.setControllerFactory(context::getBean);
		Parent root = loader.load();

		Scene scene = new Scene(root, 1100, 600);

		stage.setTitle("学生成绩分析跟踪系统");
		stage.setScene(scene);
		stage.show();

		stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
		    @Override
		    public void handle(WindowEvent event) {
		        Platform.exit();
		    }
		});

		loadCache();
	}

	/** 加载学院、专业到缓存里面取 */
	private void loadCache() {
		Completable.fromAction(() -> loadCacheData())
			.subscribeOn(Schedulers.computation())		// 后台线程加载缓存数据
			.observeOn(JavaFxScheduler.platform())
			.subscribe(() -> {							// 前台线程发送“加载成功事件”
				context.publishEvent(new AppCache.CacheReadyEvent());
			});
	}

	private Void loadCacheData() {
		CollegeMapper collegeMapper = context.getBean(CollegeMapper.class);
		MajorMapper majorMapper = context.getBean(MajorMapper.class);
		CourseMapper courseMapper = context.getBean(CourseMapper.class);
		AppCache appCache = context.getBean(AppCache.class);

		try {
			List<College> colleges = collegeMapper.selectAll();
			for (College c : colleges) {
				appCache.putCollege(c.getId(), c);
			}
			appCache.putColleges(colleges);
			logger.info("学院记录共{}条添加到缓存。", colleges.size());

			List<Major> majors = majorMapper.selectAll();
			for (Major m : majors) {
				appCache.putMajor(m.getId(), m);
			}
			appCache.putMajors(majors);
			logger.info("专业记录共{}条添加到缓存。", majors.size());

			List<Course> courses = courseMapper.selectAll();
			for (Course c : courses) {
				appCache.putCourse(c.getId(), c);
			}
			appCache.putCourses(courses);
			logger.info("专业记录共{}条添加到缓存。", courses.size());
		} catch (Exception e) {
			logger.error("加载缓存失败！", e);
		}

		return null;
	}

	public static void main(String[] args) {
		launch(args);
	}
}
